<script setup>
import { ref, onMounted } from 'vue'

const props = defineProps({
  currentLesson: String
})

const emit = defineEmits(['lesson-change'])

// 定义静态菜单项
const staticLessons = [
  { id: 'home', name: '首页' }
]

// 动态检测的组件列表
const dynamicLessons = ref([])

// 组件名称到显示名称的映射
const nameMapping = {
  'InterpolationDemo': '插值表达式',
  'PropsDemo': 'Props传值',
  'AttributeBindingDemo': '属性绑定',
  'ConditionalRenderingDemo': '条件渲染',
  'ListRenderingDemo': '列表渲染'
}

const selectLesson = (lessonId) => {
  emit('lesson-change', lessonId)
}

// 动态加载所有Demo组件并生成菜单
const loadDemoLessons = async () => {
  // 使用import.meta.glob动态导入所有Demo组件
  const modules = import.meta.glob('./*Demo.vue')
  
  const lessons = []
  for (const path in modules) {
    try {
      const componentName = path.split('/').pop().replace('.vue', '')
      
      // 根据组件名生成菜单项
      let displayName = nameMapping[componentName] || componentName.replace('Demo', '')
      
      // 特殊处理PropsDemo，因为它需要显示两个实例
      if (componentName === 'PropsDemo') {
        lessons.push({
          id: 'propsdemo',
          name: displayName,
          component: componentName
        })
        continue
      }
      
      lessons.push({
        id: componentName.toLowerCase().replace('demo', '') + 'demo',
        name: displayName,
        component: componentName
      })
    } catch (error) {
      console.error(`Failed to process component from ${path}:`, error)
    }
  }
  
  dynamicLessons.value = lessons
}

onMounted(() => {
  loadDemoLessons()
})
</script>

<template>
  <nav class="lesson-navigation">
    <ul>
      <!-- 静态菜单项 -->
      <li 
        v-for="lesson in staticLessons" 
        :key="lesson.id"
        :class="{ active: currentLesson === lesson.id }"
        @click="selectLesson(lesson.id)"
      >
        {{ lesson.name }}
      </li>
      
      <!-- 动态菜单项 -->
      <li 
        v-for="lesson in dynamicLessons" 
        :key="lesson.id"
        :class="{ active: currentLesson === lesson.id }"
        @click="selectLesson(lesson.id)"
      >
        {{ lesson.name }}
      </li>
    </ul>
  </nav>
</template>

<style scoped>
.lesson-navigation {
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,.1);
  overflow: hidden;
  height: 100%;
}

.lesson-navigation ul {
  list-style: none;
  padding: 0;
  margin: 0;
  height: 100%;
}

.lesson-navigation li {
  padding: 1rem 1.5rem;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #e9ecef;
  color: #495057;
  border-bottom: 1px solid #ddd;
}

.lesson-navigation li:last-child {
  border-bottom: none;
}

.lesson-navigation li:hover {
  background-color: #dee2e6;
}

.lesson-navigation li.active {
  background-color: #007bff;
  color: white;
}

@media (max-width: 768px) {
  .lesson-navigation {
    margin-bottom: 1rem;
    height: auto;
  }
  
  .lesson-navigation ul {
    height: auto;
  }
}
</style>